package br.ufpe.cin.msc.jrsj2.recommender.message;

import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import br.ufpe.cin.msc.jrsj2.recommender.util.ClientHash;

public class ProgramList {

	private static class MessageHandler extends DefaultHandler {
		private String clientHash;
		private String programs;

		public MessageHandler() {
			programs = new String();
		}

		@Override
		public void startElement(String uri, String localName, String qName,
				Attributes attributes) throws SAXException {
			if (qName.equals("program-list")) {
				if (attributes.getLength() == 1)
					clientHash = ClientHash.getClientHashString(attributes
							.getValue("id"));
			} else {
				if (qName.equals("current-program") || qName.equals("program"))
					if (attributes.getLength() == 1)
						programs += attributes.getValue("title") + "|";
			}
		}

		@Override
		public void endDocument() throws SAXException {
			if (programs != null)
				programs = programs.substring(0, programs.length() - 2);
		}
	}

	private MessageHandler handler;

	public void buildProgramList(String message)
			throws ParserConfigurationException, SAXException, IOException {
		SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
		InputSource is = new InputSource(new StringReader(message));
		handler = new MessageHandler();
		parser.parse(is, handler);
	}

	public String getClientHash() {
		return handler.clientHash;
	}

	public String getPrograms() {
		return handler.programs;
	}

}
